package com.ingenio.siot.adapter;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import com.ingenio.siot.Adapter;
import com.ingenio.siot.entity.Calle;
import com.ingenio.siot.entity.SentidoCalle;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

public class CalleAdapter extends Adapter{
	
	public List<Calle> devolverTodos() throws Exception{
    	Connection conn = null;
    	List<Calle> calles = new ArrayList<Calle>();
    	PreparedStatement stmt = null;
		try {
			conn = (Connection) abrirConexion();
			String sel ="SELECT * from calles";
    		stmt = (PreparedStatement) conn.prepareStatement(sel);
    		ResultSet result = stmt.executeQuery();
    		Calle c = null;
    		SentidoCalleAdapter sca = new SentidoCalleAdapter();
			
    		while(result.next()){
    			Integer id = result.getInt("IdCalle");
    			String desc = result.getString("descCalle");
    			SentidoCalle sentidoCalle = sca.devolverSentidoCalle(result.getInt("IdSentido"));
    			c = new Calle(id, desc, sentidoCalle); 
    			calles.add(c);
    		}
		}
		catch (Exception e) {
			e.printStackTrace();
			throw new Exception("Error al conectar con la base de datos.", e);
		}
    	finally{
    		//conn.close();
    		cerrarConexion(conn);
    	}
    	return calles;
    }
	
	public Calle devolverCalle(Integer idCalle) throws Exception{
		Connection conn = null;
		Calle c = null;
		PreparedStatement stmt = null;
		try{
			conn = (Connection) abrirConexion();
			String query = "SELECT * FROM calles WHERE IdCalle = ?";
			stmt = (PreparedStatement) conn.prepareStatement(query);
			stmt.setInt(1, idCalle);
			ResultSet result = stmt.executeQuery();
			if(result.next()){
				SentidoCalleAdapter sca = new SentidoCalleAdapter();
				Integer id = result.getInt("IdCalle");
				String desc = result.getString("descCalle");
				SentidoCalle sentidoCalle = sca.devolverSentidoCalle(result.getInt("IdSentido"));
				c = new Calle(id, desc, sentidoCalle);
			}
		}
		catch (Exception e){
			e.printStackTrace();
			throw new Exception("Error al conectar con la base de datos", e);
		}
		finally{
			cerrarConexion(conn);
		}
		return c;
	}
	
	public void editarDescCalle(Calle calle) throws Exception{
		Connection conn = null;
		PreparedStatement stmt = null;
		try {
			conn = (Connection) abrirConexion();
			String query = "UPDATE calles SET descCalle=? where IdCalle=?";
			stmt = (PreparedStatement)conn.prepareStatement(query);
			stmt.setString(1, calle.getDescCalle());
			stmt.setInt(2, calle.getIdCalle());
			stmt.execute();
		}
		catch (Exception e){
			e.printStackTrace();
			throw new Exception("Error al conerctar con la base de datos.", e);
		}
		finally{
			cerrarConexion(conn);
		}
	}
}
